package util

import (
	jwt "github.com/dgrijalva/jwt-go"
)

type claims struct {
	name string
	jwt.StandardClaims
}

// GenerateToken 生成登陆Token
func GenerateToken(name, tokenSecret, appName string, tokenExpiredAt int64) (string, error) {
	claim := claims{
		name,
		jwt.StandardClaims{
			ExpiresAt: tokenExpiredAt,
			Issuer:    appName,
		},
	}

	tokenClaim := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
	var jwtSecret = []byte(tokenSecret)
	token, err := tokenClaim.SignedString(jwtSecret)

	return token, err
}

// ParseToken 解析token
func ParseToken(token, tokenSecret string) (*claims, error) {
	var jwtSecret = []byte(tokenSecret)
	tokenClaim, err := jwt.ParseWithClaims(token, &claims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtSecret, nil
	})

	if tokenClaim != nil {
		if claims, ok := tokenClaim.Claims.(*claims); ok && tokenClaim.Valid {
			return claims, nil
		}
	}

	return nil, err
}
